package mr.ali.video.web.service.impl;

import lombok.extern.slf4j.Slf4j;
import mr.ali.video.web.model.Permission;
import mr.ali.video.web.model.User;
import mr.ali.video.web.mapper.UserMapper;
import mr.ali.video.web.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Mr-ali
 * @since 2024-09-17
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
   @Resource
   private UserMapper userMapper;

   /**
    * 数据库登录与权限控制
    */
   @Override
   public UserDetails getUserDetails(String username) {
      User user = userMapper.UserByUsername(username);
      if (user == null) {
         return null;
      }
      List<Permission> permissions = userMapper.SelectPermissionsById();
      int i = 0;
      String[] all = new String[permissions.size()];
      for (Permission p : permissions) {
         all[i++] = p.getAuthority();
      }
      UserDetails u = org.springframework.security.core.userdetails.User.builder().username(user.getUsername()).password(user.getPassword()).authorities(all).disabled(user.getIsEnabled() == 0).accountLocked(user.getIsLocked() == 1).build();
log.info("UserServiceImpl.getUserDetails:{}", u);
      return u;
   }

}
